package cn.virens.main.timer;

import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.virens.main.cmpt.Component;

public abstract class TimedTask extends TimerTask implements Component {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	protected final AtomicInteger run = new AtomicInteger(0);

	@Override
	public void run() {
		long s = System.currentTimeMillis();
		logger.debug("This {} thread run {} times.", name(), run.incrementAndGet());

		try {
			doRun();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			long e = System.currentTimeMillis();

			logger.debug("This {} thread runs for {} milliseconds.", name(), (e - s));
		}
	}

	protected abstract void doRun() throws Exception;

	protected abstract Integer period();

	@Override
	public String toString() {
		return "TimerTask [name=" + name() + "]";
	}

}
